package com.amado.course35Concurrent;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;

/**
 * 信号量用来做限流
 * Created by Administrator on 2018\3\18 0018.
 */
public class S17VolatileTest {
    private volatile int c = 0;
    private int sharedState = 0;
//    private static int c = 0;

    public static void main(String[] args) throws InterruptedException {
        S17VolatileTest s17VolatileTest = new S17VolatileTest();
//        s17VolatileTest.test1();
        s17VolatileTest.test2();
    }

    private void test1() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        for (int j = 0; j < 80; j++) {
            new Thread(() -> {
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (int i = 0; i < 100; i++) {
                    synchronized (S17VolatileTest.class) {
                        c++;
                    }
                }
            }).start();
        }
        countDownLatch.countDown();
        Thread.sleep(100);
        System.out.println();
        System.out.println(c);
    }

    public void test2() {
        new Thread(()->{
            nonSafeAction();
        }).start();
        new Thread(()->{
            nonSafeAction();
        }).start();
        new Thread(()->{
            nonSafeAction();
        }).start();
    }

    public void nonSafeAction() {
        while (sharedState < 100000) {
            synchronized (this) {
                int former = sharedState++;
                int latter = sharedState;
                if (former != latter - 1) {
                    System.out.println("Observed data race, former is " +
                            former + ", " + "latter is " + latter);
                }
            }
        }
    }
}
